<template>
	<div>
		<el-drawer v-model="state.isShowDialog" size="350px" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false">
			<template #header>
				<div class="flex-c-b">
					<span class="drawer-title">设置权限</span>
					<div>
						<el-button @click="closeDialog" size="default"> 取 消 </el-button>
						<el-button type="primary" @click="onSubmit" size="default"> 确 定 </el-button>
					</div>
				</div>
			</template>
			<el-tree
				ref="menuTree"
				:data="menuTreeData"
				:default-checked-keys="menuTreeIds"
				:props="menuDefaultProps"
				default-expand-all
				:check-strictly="checkStrictly"
				highlight-current
				node-key="id"
				show-checkbox
			>
			</el-tree>
		</el-drawer>
	</div>
</template>
  
<script setup lang="ts" name="systemDicDialog">
import { reactive, ref, onMounted } from 'vue';
import { SetRoleMenuBtns, GetContainsMenuBtns } from '/@/api/role/index';
import { ElMessage } from 'element-plus';
import { MenuGetPagedList } from '/@/api/menu/index';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const state = reactive({
	isShowDialog: false,
});
const props = defineProps({
	row: {
		default: function () {
			return {};
		},
		type: Object,
	},
});

const menuTreeData = ref([]);
const getInitList = ref([]);
const roleId = ref('');
const checkStrictly = ref(false);
const menuTreeIds = ref([] as any);
const menuDefaultProps = ref({
	children: 'children',
	label: function (data: any) {
		return data.title || data.name;
	},
});
// 打开弹窗
const openDialog = (id: any) => {
	roleId.value = id;
	state.isShowDialog = true;
	getTableData();
};
// 关闭弹窗
const closeDialog = () => {
	state.isShowDialog = false;
};
const getInit = async () => {
	const res = await MenuGetPagedList({ PageIndex: 1, PageSize: 9999 });
	menuTreeData.value = res.data.items;
};
getInit();
const getTableData = async () => {
	checkStrictly.value = true;
	// 获取菜单列表
	const detailsList = await GetContainsMenuBtns({ roleId: roleId.value });
	const arr = [...detailsList.data.btnIds, ...detailsList.data.menuIds] || [];
	menuTreeIds.value = arr;
	console.log(menuTreeIds);
	checkStrictly.value = false;
};
const menuTree = ref();
const onSubmit = async () => {
	const checkArr = menuTree.value.getCheckedNodes(false, true) as Array<{ id: number; type: number }>;
	console.log(checkArr);

	const menuIds: number[] = [];
	const btnIds: number[] = [];

	if (checkArr.length) {
		checkArr.forEach((v) => {
			(v.type === 1 ? menuIds : btnIds).push(v.id);
		});
	}

	const params = {
		roleId: roleId.value,
		menuIds,
		btnIds,
	};
	await SetRoleMenuBtns(params);
	console.log(params);
	ElMessage.success('角色权限设置成功');
	closeDialog();
	emit('refresh');
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>
<style scoped lang="scss">
.menu-data-tree {
	padding: 5px;
}
</style>

